/*
 * ChatView.java
 */

package chat;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.text.DateFormat;
import java.util.Date;
import javax.swing.DefaultListModel;
import org.jdesktop.application.Action;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;

/**
 * The application's main frame.
 */
public class ChatView extends FrameView implements Runnable {

    private Socket socket;
    private DataOutputStream dout;
    private DataInputStream din;
    private ckinUtils c = new ckinUtils();
    public String nick = "";
    public String oldnick;
    Date now = new Date();
    DefaultListModel listModel = new DefaultListModel();

    public void start(String host, int port){
        input.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                processMessage(e.getActionCommand());
            }
        });
        try {
            socket = new Socket(host, port);
            System.out.println("connected to "+socket);
            din = new DataInputStream(socket.getInputStream());
            dout = new DataOutputStream(socket.getOutputStream());
            new Thread(this).start();
            dout.writeUTF("Talk|-|System|-|***" + nick +" has joined the chat room***");
        } catch(IOException ie) {
            System.out.println(ie);
            printl("!!!Error Connecting To Server!!!");
        }
    }

    public ChatView(SingleFrameApplication app) {
        super(app);
        initComponents();
        clientlist.setModel(listModel);
        start("127.0.0.1", 1337);
        send.setEnabled(false);
        input.setEnabled(false);
    }

    private void processMessage(String message) {
        try {
            dout.writeUTF("Talk|-|" + nick + "|-|" + message);
            input.setText("");
        } catch(IOException ie) {
            System.out.println(ie);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        input = new javax.swing.JTextField();
        send = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        log = new javax.swing.JTextArea();
        jScrollPane2 = new javax.swing.JScrollPane();
        clientlist = new javax.swing.JList();
        login = new javax.swing.JButton();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();

        mainPanel.setName("mainPanel"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(chat.ChatApp.class).getContext().getResourceMap(ChatView.class);
        input.setText(resourceMap.getString("input.text")); // NOI18N
        input.setName("input"); // NOI18N

        send.setText(resourceMap.getString("send.text")); // NOI18N
        send.setName("send"); // NOI18N
        send.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendActionPerformed(evt);
            }
        });

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        log.setColumns(20);
        log.setEditable(false);
        log.setLineWrap(true);
        log.setRows(5);
        log.setName("log"); // NOI18N
        log.setSelectionColor(resourceMap.getColor("log.selectionColor")); // NOI18N
        jScrollPane1.setViewportView(log);

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        clientlist.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        clientlist.setName("clientlist"); // NOI18N
        jScrollPane2.setViewportView(clientlist);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(chat.ChatApp.class).getContext().getActionMap(ChatView.class, this);
        login.setAction(actionMap.get("performLogin")); // NOI18N
        login.setText(resourceMap.getString("login.text")); // NOI18N
        login.setName("login"); // NOI18N

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                        .addComponent(input, javax.swing.GroupLayout.DEFAULT_SIZE, 379, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(send))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 446, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(login, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 96, Short.MAX_VALUE))
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 262, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 262, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(input, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(send)
                    .addComponent(login, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        jMenuItem1.setAction(actionMap.get("performLogin")); // NOI18N
        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N
        jMenuItem1.setName("jMenuItem1"); // NOI18N
        fileMenu.add(jMenuItem1);

        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        setComponent(mainPanel);
        setMenuBar(menuBar);
    }// </editor-fold>//GEN-END:initComponents

    private void sendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendActionPerformed
        processMessage(input.getText());
    }//GEN-LAST:event_sendActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList clientlist;
    private javax.swing.JTextField input;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea log;
    private javax.swing.JButton login;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JButton send;
    // End of variables declaration//GEN-END:variables

    public void run() throws NullPointerException {
        try {
            while (true) {
                String message = din.readUTF();
                resolveRequest(message);
            }
        } catch(IOException ie) {
            System.out.println(ie);
        }
    }

    public void printl(String l) {
        log.append("System[" + DateFormat.getTimeInstance(DateFormat.SHORT).format(now) + "]: " + l);
        System.out.println("System[" + DateFormat.getTimeInstance(DateFormat.SHORT).format(now) + "]: " + l);
    }

    @Action
    public void performLogin() throws IOException, ClassNotFoundException {
        oldnick = nick;
        nick = c.Input("Please enter a new nickname.");
        dout.writeUTF("Login|-|" + nick + "|-|" + oldnick);
        send.setEnabled(true);
        input.setEnabled(true);
        login.setVisible(false);
        mainPanel.setDoubleBuffered(true);

    }

    private void resolveRequest(String in) {
        String[] packet = in.split("\\|-\\|");
        if(packet[0].equals("Talk")){
            log.append(packet[1] + "\n");
        }
        if(packet[0].equals("clUpdate")){
            if(Boolean.parseBoolean(packet[2]))
                listModel.addElement(packet[1]);
            else
                listModel.removeElement(packet[1]);
        }
    }
}
